const log4js = require('log4js');
const log4jsConf = require('./log4jsConf')
const dateUtils = require('../../utils/dateUtils')
const {
	$_ULOG,
} = require('./logger')

module.exports = function() {
	log4js.configure(log4jsConf);

	// Console replacement
	// V1 used to allow you to replace the node.js console functions with versions that would log to a log4js appender. This used to cause some weird errors, so I decided it was better to remove it from the log4js core functionality. 
	const logger = log4js.getLogger('console');
	console.log = logger.info.bind(logger);
	return logMiddleWare;
}

function logMiddleWare(req, res, next) {
	$_ULOG.call(req, `---请求进入-[${req.path}]-logger/index.js---`);
	$_ULOG.call(req, `---request日志开始: ${req.path}, 开始时间:${new Date()}---`)
	let start = Date.now();
	res.on("finish", function() {
		let levels = log4js.levels,
			level = levels.TRACE,
			info = '';
		if (res.statusCode >= 300) level = levels.WARN;
		if (res.statusCode >= 400) level = levels.ERROR;
		info += JSONLog(req, res, start);
		$_ULOG.call(req, info)
		let result = ''
		if (typeof res._$OUT == 'object') {
			result = JSON.stringify(res._$OUT)
		} else {
			result = res._$OUT
		}
		$_ULOG.call(req, `--- 结束时间:${new Date()} 返回结果:[${result}]`)
	});
	return next();
}

function JSONLog(req, res, start) {
	let info = {};
	info.datetime = dateUtils.getMSTime()
	info.api = req.originalUrl.split("?")[0]
	info.reqip = req.ip
	info.reqips = req.ips
	info.method = req.method
	info.query = req.query
	info.body = req.body
	info.session = req.session
	info.headers = req.headers;
	info.originalUrl = req.originalUrl;
	info.statusCode = (res.__statusCode || res.statusCode)
	info.time = (Date.now() - start)
	return JSON.stringify(info)
}